<template>
  <div class="container">
    <div v-if="showFlag" style="height: 100%;">
      <div class="top">
        <div>
          <span>
            <span>名称：&nbsp;&nbsp;</span>
            <el-input v-model="searchData.name" style="width: 240px" />
          </span>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <el-button type="primary" plain @click="search">查询</el-button>
          <el-button type="primary" plain @click="resetSearch">重置</el-button>
        </div>
        <el-button type="primary" plain @click="addData">新增</el-button>
      </div>
      <el-table :data="tableData" style="width: 100%" v-loading="loading" height="calc(100% - 20px)">
        <el-table-column type="index" label="序号" width="55"> </el-table-column>
        <el-table-column prop="name" label="名称"> </el-table-column>
        <el-table-column prop="createBy" label="创建人"> </el-table-column>
        <el-table-column prop="createTime" label="创建时间"> </el-table-column>
        <el-table-column prop="date" label="操作">
          <template #default="scope">
            <el-icon title="编辑" @click="tableEdit(scope.row)">
              <Edit />
            </el-icon>
            &nbsp;
            <el-icon title="删除" @click="tableDel(scope.row)">
              <Delete />
            </el-icon>
          </template> </el-table-column>
      </el-table>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog title="应急组织管理" v-model="open" width="500px" append-to-body>
      <span>名称：&nbsp;&nbsp;</span>
      <el-input v-model="name" style="width: 240px" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <div v-if="!showFlag" style="height: 100%;">
      <div class="brn">
        <h3>防洪指挥部</h3>
        <el-button type="primary" @click="save">保存</el-button>
      </div>
      
      <el-form ref="postRef" :model="form" :rules="rules" label-width="auto">
        <el-form-item label="总指挥" prop="commander">
          <el-select v-model="form.commander" placeholder="请选择" clearable
           >
            <el-option v-for="item in options" :key="item.userId" :label="item.userName" :value="item.userName" />
          </el-select>
        </el-form-item>
        <el-form-item label="副总指挥" prop="deputyCommander" style="width: 100%;">
          <el-select filterable v-model="form.deputyCommander" placeholder="请选择" clearable multiple
           >
            <el-option v-for="item in options" :key="item.userId" :label="item.userName" :value="item.userName" >
              <span style="float: left; margin-right: 10px;">{{item.userName}} <span v-show="item.deptName && item.deptName!= null">{{"&nbsp;&nbsp;--&nbsp;&nbsp;" + item.deptName}}</span></span>
              <!-- <span style="float: left; margin-right: 10px;">{{ item.userName + "&nbsp;&nbsp;--&nbsp;&nbsp;" +item.deptName}}</span> -->
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div>
        <el-button @click="addTable">新增</el-button>
        <hr>
        <div style="height: 68vh; overflow-y: auto;">
        <div v-for="(item,index) in details" :key="index" style="margin-bottom: 20px;">
          <div style="display: flex;justify-content: flex-end;">
            <el-button @click="delTable(index)">删除</el-button>
          </div>
          <el-table :data="item" style="width: 100%" :span-method="(obj)=>arraySpanMethod(obj,item)">
            <el-table-column prop="officeName" label="名称">
              <template #default="scope">
                <el-input v-model="scope.row.officeName" />
              </template>
            </el-table-column>
            <el-table-column prop="position" label="职务">
              <template #default="scope">
                <el-input v-model="scope.row.position"/>
              </template>
            </el-table-column>
            <el-table-column label="姓名">
              <template #default="scope">
                <el-select v-model="scope.row.userId" placeholder="请选择" clearable
                  @change="(val)=>userChange(val,scope.row)">
                  <el-option v-for="item in options" :key="item.userId" :label="item.userName" :value="item.userId" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="phonenumber" label="联系电话"> </el-table-column>
            <el-table-column prop="date" label="操作">
              <template #default="scope">
                <el-icon title="新增" @click="add(scope.row,item)">
                  <Plus />
                </el-icon>
                &nbsp;
                <el-icon title="删除" @click="del(scope.row,item,scope.$index)">
                  <Delete />
                </el-icon>
              </template> </el-table-column>
          </el-table>
        </div>
      </div>
      </div>
    </div>
  </div>
</template>

<script setup>
  import {
    ElMessage,
    ElMessageBox
  } from 'element-plus'
  import {
    getOrg,
    delOrg,
    addOrg,
    getPersonBy,
    saveOrg
  } from "@/api/work";
  const {
    proxy
  } = getCurrentInstance();

  const options = ref([])
  const all = ref([])

  function getPerson() {
    getPersonBy().then(res => {
      options.value = res.rows
      all.value = JSON.parse(JSON.stringify(res.rows))
    })
  }
  getPerson()

  const open = ref(false)
  const searchData = ref({
    name: ''
  })

  function search() {
    getOrg(searchData.value).then(res => {
      tableData.value = res.rows
    })
  }

  function resetSearch() {
    searchData.value = {
      name: '',
    }
    getList()
  }

  const tableData = ref([])
  const loading = ref(true);
  function getList() {
    loading.value = true
    getOrg().then(res => {
      tableData.value = res.rows
      loading.value = false
    })
  }
  getList()

  const name = ref("")

  function addData() {
    open.value = true
    name.value = ''
    form.value = {}
    details.value = []
  }

  function submitForm() {
    if (name.value == '') return ElMessage({
      type: 'info',
      message: '请输入名称',
    })
    addOrg({name:name.value}).then(res => {
      open.value = false
      showFlag.value = false
      form.value.organizationId = res.organizationId
    })
  }

  function tableDel(data) {
    ElMessageBox.confirm(
        '确认删除吗？',
        'Warning', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
      .then(() => {
        delOrg(data.id).then(res => {
          ElMessage({
            type: 'success',
            message: '已删除',
          })
          getList()
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
  }

  function tableEdit(row) {
    let list = Object.values(row.details)
    details.value = list
    form.value = row
    showFlag.value = false
    if(row.deputyCommander&&row.deputyCommander !=""){
      row.deputyCommander = row.deputyCommander.split(",")
    }else{
      row.deputyCommander = []
    }
  }
  function arraySpanMethod({
    row,
    column,
    rowIndex,
    columnIndex
  },list){
    if (columnIndex == 0 ) {
      if (rowIndex == 0 ) {
        return [list.length, 1];
      } else {
        return [0, 0];
      }
    }
  }

  function cancel() {
    open.value = false
  }
  const showFlag = ref(true)

  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      postCode: undefined,
      postName: undefined,
      phone: undefined
    },
    rules: {
      // phone: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
      // postName: [{ required: true, message: "岗位名称不能为空", trigger: "blur" }],
      // postCode: [{ required: true, message: "岗位编码不能为空", trigger: "blur" }],
      // postSort: [{ required: true, message: "岗位顺序不能为空", trigger: "blur" }],
    }
  });
  const {
    queryParams,
    form,
    rules
  } = toRefs(data);

  const details = ref([
    [{}]
  ])

  function addTable() {
    details.value.push([{}])
  }

  function delTable(index) {
    details.value.splice(index, 1)
  }

  function userChange(val, row) {
    all.value.forEach(item => {
      if (item.userId == val) {
        row.phonenumber = item.phonenumber
      }
    })
  }

  function add(row, item) {
    item.push({})
  }

  function del(row,list,index) {
    list.splice(index, 1)
  }
  //详情保存
  function save(){
    if(!form.value.organizationId){
      form.value.organizationId = form.value.id
    }
    if(form.value.deputyCommander.length){
      form.value.deputyCommander = form.value.deputyCommander.join(',')
    }else{
      form.value.deputyCommander = ''
    }
    let obj = {}
    if(details.value.length){
      details.value.forEach((item,index)=>{
        obj[index+1] = item
      })
    }
    form.value.detailsMap = obj
    
    saveOrg(form.value).then(res=>{
      showFlag.value = true
      getList()
    })
  }
</script>

<style lang='scss' scoped>
  :deep(.el-table--border::before) {
    width: 0px;;
  }
  :deep(.el-table--border::after) {
    width: 0px;;
  }
  .container {
    height: 100%;
    width: 100%;
    padding: 20px;
  }

  .top {
    height: 40px;
    line-height: 40px;
    display: flex;
    justify-content: space-between;
  }

  .end {
    justify-content: flex-end;
  }

  :deep(.el-table .el-table__cell) {
    text-align: center;
  }
  .brn{
    display:flex;
    justify-content: space-between;
  }
</style>